"""change url and html to fields

Revision ID: 445a101b044e
Revises: 4d34dbcbed58
Create Date: 2019-08-11 10:02:17.801164

"""
from alembic import op
import sqlalchemy as sa
from flaskblog.md import markdown


# revision identifiers, used by Alembic.
revision = "445a101b044e"
down_revision = "4d34dbcbed58"
branch_labels = None
depends_on = None

post_table = sa.table(
    "post",
    sa.column("id", sa.Integer()),
    sa.column("date", sa.DateTime()),
    sa.column("content", sa.Text()),
    sa.column("html", sa.Text()),
    sa.column("toc", sa.Text()),
    sa.column("url", sa.String(length=80)),
    sa.column("slug", sa.String(length=100)),
)


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column("post", sa.Column("html", sa.Text(), nullable=True))
    op.add_column("post", sa.Column("toc", sa.Text(), nullable=True))
    op.add_column("post", sa.Column("url", sa.String(length=80), nullable=True))
    # ### end Alembic commands ###
    conn = op.get_bind()
    for row in conn.execute(post_table.select()).fetchall():
        op.execute(
            post_table.update()
            .where(post_table.c.id == row["id"])
            .values(
                url="/{}/{}".format(row["date"].strftime("%Y/%m-%d"), row["slug"]),
                html=markdown(row["content"]),
                toc=markdown.renderer.render_toc(),
            )
        )


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column("post", "url")
    op.drop_column("post", "toc")
    op.drop_column("post", "html")
    # ### end Alembic commands ###
